package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ruffian.library.widget.RRelativeLayout;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.api.ApiRequest;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.MemberBindEvent;
import cn.mumzone.pos.event.MemberChangeEvent;
import cn.mumzone.pos.event.RefreshMemberLevelEvent;
import cn.mumzone.pos.model.BillDetailEntity;
import cn.mumzone.pos.model.LoginEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.RechargeDetailEntity;
import cn.mumzone.pos.model.SunMiPayResponse;
import cn.mumzone.pos.presenter.MemberDetailPresenter;
import cn.mumzone.pos.presenter.SettleAccountPresenter;
import cn.mumzone.pos.presenter.contract.MemberDetailContract;
import cn.mumzone.pos.ui.adapter.ADA_Member_Baby;
import cn.mumzone.pos.ui.fragment.member.FRA_Coupon;
import cn.mumzone.pos.ui.fragment.member.FRA_DepositGoods;
import cn.mumzone.pos.ui.fragment.member.FRA_TimesCard;
import cn.mumzone.pos.ui.widgets.StepView;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.ui.widgets.tablayout.MagicIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.ViewPagerHelper;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.CommonNavigator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.IPagerIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.abs.IPagerTitleView;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.indicators.LinePagerIndicator;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import cn.mumzone.pos.ui.widgets.tablayout.buildins.commonnavigator.titles.SimplePagerTitleView;
import cn.mumzone.pos.ui.widgets.util.StringSpanUtils;
import cn.mumzone.pos.util.AppUtil;
import cn.mumzone.pos.util.BillUtil;
import cn.mumzone.pos.util.print.PrintEntity;
import cn.mumzone.pos.util.print.PrinterService;

import static cn.mumzone.pos.AppConstants.SUNMI_PAY_ACTION;

/**
 * Created By Dlx
 * on 2019/7/3
 */
public class ACT_MemberDetail extends BaseActivity<MemberDetailPresenter> implements MemberDetailContract.View {

    @BindView(R.id.root_view)
    LinearLayout clRootView;
    @BindView(R.id.iv_more)
    AppCompatImageView ivMore;
    @BindView(R.id.iv_member_portrait)
    AppCompatImageView ivMemberPortrait;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.tv_member_level)
    TextView tvMemberLevel;
    @BindView(R.id.tv_member_phone)
    TextView tvMemberPhone;
    @BindView(R.id.iv_member_birthday)
    AppCompatImageView ivMemberBirthday;
    @BindView(R.id.tv_member_birthday)
    TextView tvMemberBirthday;
    @BindView(R.id.tv_member_balance)
    TextView tvMemberBalance;
    @BindView(R.id.tv_member_credit)
    TextView tvMemberCredit;
    @BindView(R.id.tv_last_consume_content)
    TextView tvLastConsumeContent;
    @BindView(R.id.tv_member_grade_content)
    TextView tvMemberGradeContent;
    @BindView(R.id.tv_age_content)
    TextView tvAgeContent;
    @BindView(R.id.tv_relation_content)
    TextView tvRelationContent;
    @BindView(R.id.tv_mom_status_content)
    TextView tvMomStatusContent;
    @BindView(R.id.tv_register_time_content)
    TextView tvRegisterTimeContent;
    @BindView(R.id.tv_introduce_content)
    TextView tvIntroduceContent;
    @BindView(R.id.indicator_member_detail)
    MagicIndicator indicatorMemberDetail;
    @BindView(R.id.rlv_member_baby)
    RecyclerView rlvBaby;
    @BindView(R.id.vp_member)
    ViewPager mMemberViewPager;

    private String memberPhone;

    @BindView(R.id.rl_no_babies)
    RRelativeLayout rlNoBabies;

    private final int REQUEST_CODE_MODIFY_MEMBER = 0;
    private final int REQUEST_CODE_ADD_BABY = 1;
    public static final int REQUEST_CODE_MODIFY_BABY = 2;

    private MemberEntity memberEntity;
    private String memberId;

    private ADA_Member_Baby babyAdapter;


    private boolean onlySaleGoods;

    //充值相关弹窗
    private AlertDialog payTypeSelectDialog;
    private String payType;

    private AlertDialog rechargeSelectDialog;
    private EditText etRecharge;

    //微信支付宝支付
    private AlertDialog payDialog;
    private EditText etScanCode;
    private ImageView ivScanRemind;
    private ImageView ivPayType;
    private TextView tvPayType;
    private AlertDialog alipayChooseDialog;

    private AlertDialog sunMiPayErrorDialog;
    private PosAlertDialog sunMiAlertDialog;

    private AlertDialog bankPosPayDialog;
    private StepView svProgress;
    private LoadingButton lbSendBankPay;
    private LoadingButton lbSettleDone;
    private LoadingButton lbRetryPay;

    private AlertDialog bankDefaultPayDialog;


    private AlertDialog cashPayDialog;
    private EditText etCash;

    private String toPayAmount = "";


    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        memberPhone = extras.getString("memberPhone");
        memberId = extras.getString("memberId");


        onlySaleGoods = AppUtil.isOnlyHasGoodsBusiness();
    }


    @Override
    protected void initEventAndData() {
        mPresenter.onEvent();
        mPresenter.initVariable(memberId, memberPhone);
        mPresenter.getMemberDetail(memberPhone);
        rlvBaby.setNestedScrollingEnabled(false);
        rlvBaby.setLayoutManager(new LinearLayoutManager(this));


        final Bundle bundle = new Bundle();
        bundle.putString("memberId", memberId);
        bundle.putString("memberPhone", memberPhone);

        final List<BaseFragment> fragments = new ArrayList<>();
        if (!onlySaleGoods) {
            fragments.add(new FRA_TimesCard());
        }
        fragments.add(new FRA_Coupon());
        fragments.add(new FRA_DepositGoods());
        mMemberViewPager.setOffscreenPageLimit(fragments.size());
        mMemberViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                BaseFragment baseFragment = fragments.get(position);
                baseFragment.setArguments(bundle);
                return baseFragment;
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });

        initRechargeDialogs();

        initSunMiReceiver();

    }

    private void initRechargeDialogs() {

        initPayTypeSelectDialog();

        initRechargeDialog();

        initCashPayDialog();

        initScanPayDialog();

        initSunMiPayErrorDialog();

        initAlipayChooseDialog();

        initBankPosPayDialog();

        initBankDefaultPayDialog();
    }

    private void initPayTypeSelectDialog() {
        payTypeSelectDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_recharge_pay_type)
                .setUseRadiusBg(false)
                .setDialogNoConfirm()
                .setDialogTitle("选择充值方式")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payType = "";
                switch (v.getId()) {
                    case R.id.rl_wx_pay:
                        payType = BillUtil.PAY_TYPE_WE_CHAT;
                        break;
                    case R.id.rl_ali_pay:
                        payType = BillUtil.PAY_TYPE_ALI;
                        break;
                    case R.id.rl_cash_pay:
                        payType = BillUtil.PAY_TYPE_CASH;
                        break;
                    case R.id.rl_card_pay:
                        payType = BillUtil.PAY_TYPE_BANK;
                        break;
                }
                showRechargeDialog(payType);
                closeDialog(payTypeSelectDialog);

            }
        };
        payTypeSelectDialog.setOnClickListener(R.id.rl_wx_pay, onClickListener);
        payTypeSelectDialog.setOnClickListener(R.id.rl_ali_pay, onClickListener);
        payTypeSelectDialog.setOnClickListener(R.id.rl_cash_pay, onClickListener);
        payTypeSelectDialog.setOnClickListener(R.id.rl_card_pay, onClickListener);

        if (LoginEntity.STORE_TYPE_SHOP == AppConstants.TEMP_SHOP_STORE_TYPE) {
            payTypeSelectDialog.getView(R.id.rl_cash_pay).setVisibility(View.VISIBLE);
        } else {
            payTypeSelectDialog.getView(R.id.rl_cash_pay).setVisibility(View.GONE);
        }
    }


    private void initRechargeDialog() {
        rechargeSelectDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_recharge)
                .setUseRadiusBg(false)
                .setDialogUseBack(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeDialog(rechargeSelectDialog);
                        showDialog(payTypeSelectDialog);
                    }
                })
                .setDialogNoConfirm()
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        rechargeSelectDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        etRecharge = rechargeSelectDialog.getView(R.id.et_recharge);
        PosKeyBoardView kbRecharge = rechargeSelectDialog.getView(R.id.kb_recharge);
        MoneyFormatUtil.setTextFilter(etRecharge);
        kbRecharge.attachTo(etRecharge, 999999.99, "");
        kbRecharge.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                toPayAmount = etRecharge.getText().toString().trim();
                if (TextUtils.isEmpty(toPayAmount)) {
                    showError("请输入充值金额");
                    return;
                }
                if (Double.parseDouble(toPayAmount) == 0) {
                    showError("充值金额不能为0");
                    return;
                }

                showPayDialog();
                closeDialog(rechargeSelectDialog);
            }
        });
    }


    private void showRechargeDialog(String payType) {
        switch (payType) {
            case BillUtil.PAY_TYPE_WE_CHAT:
                rechargeSelectDialog.setText(R.id.tv_dialog_title, "微信充值");
                break;
            case BillUtil.PAY_TYPE_ALI:
                rechargeSelectDialog.setText(R.id.tv_dialog_title, "支付宝充值");
                break;
            case BillUtil.PAY_TYPE_CASH:
                rechargeSelectDialog.setText(R.id.tv_dialog_title, "现金充值");
                break;
            case BillUtil.PAY_TYPE_BANK:
                rechargeSelectDialog.setText(R.id.tv_dialog_title, "银行卡充值");
                break;
        }
        etRecharge.setText("");
        showDialog(rechargeSelectDialog);
    }

    /**
     * 初始化扫码弹窗
     */
    private void initScanPayDialog() {

        payDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_scan_gun_hint)
                .setUseRadiusBg(false)
                .setDialogUseBack(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeDialog(payDialog);
                        if (AppUtil.isAppSunMiVersion() && AppUtil.isFacePayPos() && BillUtil.PAY_TYPE_ALI.equals(payType)) {
                            showDialog(alipayChooseDialog);
                        } else {
                            showRechargeDialog(payType);
                        }
                    }
                })
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        etScanCode = payDialog.getView(R.id.et_scan_code);
        ivScanRemind = payDialog.getView(R.id.iv_scan_remind);
        etScanCode.setInputType(InputType.TYPE_NULL);
        EditTextUtil.hideSoftInputMethod(this, etScanCode);
        // 监听扫码输入完成的监听
        etScanCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == KeyEvent.ACTION_DOWN) {
                    String code = etScanCode.getText().toString().trim();
//                     下传到 P 层处理逻辑
                    mPresenter.executeScanCode(code, toPayAmount);
                }
                return true;
            }
        });
        payDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        ivPayType = payDialog.getView(R.id.iv_pay_type);
        tvPayType = payDialog.getView(R.id.tv_pay_type);
        TextView tvScanRemind = payDialog.getView(R.id.tv_scan_remind);
        SpannableStringBuilder remindStr = StringSpanUtils.init()
                .addForegroundColorHighLightWithKey(getResources().getColor(R.color.order_status_service), "请使用扫码枪扫描顾客二维码...", "扫码枪")
                .setForeColorWithKeyAndPosition("二维码", 0, getResources().getColor(R.color.order_status_service)).build();
        tvScanRemind.setText(remindStr);

    }

    private void initAlipayChooseDialog() {
        alipayChooseDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_alipay_choose)
                .setUseRadiusBg(false)
                .setDialogUseBack(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeDialog(alipayChooseDialog);
                        showRechargeDialog(payType);
                    }
                })
                .setDialogTitle("支付宝支付")
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        alipayChooseDialog.setOnClickListener(R.id.tv_alipay_scan, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPayDialogByStatus(true, true, true);
                closeDialog(alipayChooseDialog);
            }
        });

        alipayChooseDialog.setOnClickListener(R.id.tv_alipay_face, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.executeFacePay(toPayAmount);
                // TODO: 2019/8/5 扫脸支付
                closeDialog(alipayChooseDialog);
                ImageView ivClose = payDialog.getView(R.id.iv_dialog_close);
                ivClose.setVisibility(View.GONE);
            }
        });
    }

    private void initBankPosPayDialog() {
        bankPosPayDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_bank_pos_pay)
                .setUseRadiusBg(false)
                .setDialogUseBack(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeDialog(bankPosPayDialog);
                        showDialog(rechargeSelectDialog);
                    }
                })
                .setDialogTitle("银行卡支付")
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        svProgress = bankPosPayDialog.getView(R.id.sv_progress);
        svProgress.setProgressText("发送账单至POS", "POS刷卡", "结账成功");
        lbSendBankPay = bankPosPayDialog.getView(R.id.lb_bank_confirm);
        lbSettleDone = bankPosPayDialog.getView(R.id.lb_settle_done);
        lbRetryPay = bankPosPayDialog.getView(R.id.lb_retry);

        bankPosPayDialog.setOnClickListener(R.id.lb_bank_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lbSendBankPay.startLoading("正在发送", bankPosPayDialog.getView(R.id.iv_dialog_close));
                mPresenter.settleOrderWithBank(toPayAmount);
                showBankPayByStatus(false, false);
            }
        });
        bankPosPayDialog.setOnClickListener(R.id.lb_settle_done, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lbSettleDone.startLoading("正在完成", bankPosPayDialog.getView(R.id.iv_dialog_close));
                mPresenter.requestOrderInfoAfterTimeOut();
            }
        });
        bankPosPayDialog.setOnClickListener(R.id.lb_retry, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lbRetryPay.startLoading("正在发送", bankPosPayDialog.getView(R.id.iv_dialog_close));
                mPresenter.settleOrderWithBank(toPayAmount);
            }
        });
    }

    private void showBankPayByStatus(boolean isTimeOut, boolean isFirst) {
        bankPosPayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(toPayAmount));
        if (isTimeOut) {
            bankPosPayDialog.getView(R.id.iv_dialog_back).setVisibility(View.GONE);
            bankPosPayDialog.getView(R.id.group_progress).setVisibility(View.GONE);
            bankPosPayDialog.getView(R.id.group_bottom_confirm).setVisibility(View.GONE);
            bankPosPayDialog.getView(R.id.group_time_out).setVisibility(View.VISIBLE);
        } else {
            bankPosPayDialog.getView(R.id.group_progress).setVisibility(View.VISIBLE);
            bankPosPayDialog.getView(R.id.group_time_out).setVisibility(View.GONE);
            ImageView ivProgress = bankPosPayDialog.getView(R.id.iv_progress);
            if (isFirst) {
                svProgress.setCurrentPosition(0);
                bankPosPayDialog.getView(R.id.iv_dialog_back).setVisibility(View.VISIBLE);
                bankPosPayDialog.getView(R.id.group_bottom_confirm).setVisibility(View.VISIBLE);
                bankPosPayDialog.setText(R.id.tv_progress, "第一步，发送账单至POS");
                bankPosPayDialog.setText(R.id.tv_progress_remind, "请保证pos网络连接顺畅！");
                ivProgress.setImageResource(R.drawable.svg_ic_bank_pay_send);
            } else {
                svProgress.setCurrentPosition(1);
                bankPosPayDialog.getView(R.id.iv_dialog_back).setVisibility(View.GONE);
                ivProgress.setImageResource(R.drawable.svg_ic_bank_pay_waiting);
                bankPosPayDialog.setText(R.id.tv_progress, "第二步，使用拉卡拉pos刷卡支付 (60s)");
                bankPosPayDialog.setText(R.id.tv_progress_remind, "未收到账单？请保证pos网络顺畅！");
                bankPosPayDialog.getView(R.id.group_bottom_confirm).setVisibility(View.GONE);

            }
        }
        showDialog(bankPosPayDialog);
    }

    private void initBankDefaultPayDialog() {
        bankDefaultPayDialog = new PosDialog.PosBuilder(mContext, PosDialog.CONFIRM_TYPE_SINGLE_CHOICE_SHADOW)
                .setRealDialogContent(R.layout.dialog_bank_pay)
                .setUseRadiusBg(false)
                .setDialogUseBack(true, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        closeDialog(bankDefaultPayDialog);
                        showDialog(rechargeSelectDialog);
                    }
                })
                .setDialogTitle("银行卡支付")
                .setSingleConfirmText("已支付成功")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .setOnSingleConfirmListener(new AlertDialog.Builder.OnSingleConfirmListener() {
                    @Override
                    public void onConfirmClicked(AlertDialog dialog) {
                        LoadingButton loadingButton = bankDefaultPayDialog.getView(R.id.lb_confirm);
                        loadingButton.startLoading("正在完成", bankDefaultPayDialog.getView(R.id.iv_dialog_close));
                        mPresenter.settleOrderWithBank(toPayAmount);
                    }
                })
                .create();
    }

    private void showPayDialog() {
        mPresenter.updatePayTypeMap(true, payType, toPayAmount);
        switch (payType) {
            case BillUtil.PAY_TYPE_WE_CHAT:
                showPayDialogByStatus(false, true, true);
                break;
            case BillUtil.PAY_TYPE_ALI:
                if (AppUtil.isAppSunMiVersion() && AppUtil.isFacePayPos()) {
                    showDialog(alipayChooseDialog);
                } else {
                    showPayDialogByStatus(true, true, true);
                }
                break;
            case BillUtil.PAY_TYPE_CASH:
                mPresenter.settleOrderWithCash(etRecharge.getText().toString().trim());
                break;
            case BillUtil.PAY_TYPE_BANK:
                if (AppConstants.TEMP_SHOP_PAY_CNL == LoginEntity.PAY_CNL_ZJ) {
                    showBankPayByStatus(false, true);
                } else {
                    bankDefaultPayDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(toPayAmount));
                    showDialog(bankDefaultPayDialog);
                }
                break;
        }
    }

    private void showPayDialogByStatus(boolean isAlipay, boolean isScan, boolean isShowBack) {
        payDialog.setText(R.id.tv_dialog_title, isAlipay ? "支付宝支付" : "微信支付");
        payDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(toPayAmount));
        ivPayType.setImageResource(isAlipay ? R.drawable.svg_ic_pay_dialog_alipay : R.drawable.svg_ic_pay_dialog_wxpay);
        sunMiPayErrorDialog.setText(R.id.tv_pay_type, isAlipay ? "支付宝支付" : "微信支付");
        sunMiPayErrorDialog.setText(R.id.tv_dialog_title, isAlipay ? "支付宝支付" : "微信支付");
        sunMiPayErrorDialog.setText(R.id.tv_pay_amout, StringUtils.getFormattedMoneyWithUnit(toPayAmount));
        ImageView ivSunMIPayType = sunMiPayErrorDialog.getView(R.id.iv_pay_type);
        if (isScan) {
            ImageView ivClose = payDialog.getView(R.id.iv_dialog_close);
            ivClose.setVisibility(View.VISIBLE);
            etScanCode.setVisibility(View.VISIBLE);
            etScanCode.requestFocus();
            tvPayType.setText(isAlipay ? "支付宝支付" : "微信支付");
        } else {
            etScanCode.setVisibility(View.GONE);
            ImageView ivClose = payDialog.getView(R.id.iv_dialog_close);
            ivClose.setVisibility(View.GONE);
        }

        if (isShowBack) {
            ImageView ivBack = payDialog.getView(R.id.iv_dialog_back);
            ivBack.setVisibility(View.VISIBLE);
            if (isAlipay) {
                payDialog.setText(R.id.tv_dialog_title, "支付宝扫码支付");
            }
        } else {
            ImageView ivBack = payDialog.getView(R.id.iv_dialog_back);
            ivBack.setVisibility(View.GONE);
        }

        ivScanRemind.setImageResource(isScan ? R.drawable.svg_ic_pay_dialog_scan_remind : R.drawable.svg_ic_pay_waitting);
        ivPayType.setVisibility(isScan ? View.VISIBLE : View.INVISIBLE);
        tvPayType.setVisibility(isScan ? View.VISIBLE : View.INVISIBLE);

        payDialog.getView(R.id.tv_scan_remind).setVisibility(isScan ? View.VISIBLE : View.GONE);
        payDialog.getView(R.id.tv_pay_remind).setVisibility(isScan ? View.GONE : View.VISIBLE);
        payDialog.getView(R.id.tv_pay_remind_time).setVisibility(isScan ? View.GONE : View.VISIBLE);
        etScanCode.requestFocus();
        showDialog(payDialog);
    }

    private void initSunMiPayErrorDialog() {
        sunMiPayErrorDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_sunmi_pay_error)
                .setUseRadiusBg(false)
                .setDialogTitle("微信支付")
                .setDialogNoConfirm()
                .fromRight(true)
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .create();
        ImageView ivClose = sunMiPayErrorDialog.getView(R.id.iv_dialog_close);
        ivClose.setVisibility(View.GONE);
        sunMiPayErrorDialog.setOnClickListener(R.id.lb_refresh, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadingButton lbConfirm = sunMiPayErrorDialog.getView(R.id.lb_refresh);
                lbConfirm.startLoading("正在刷新");
                mPresenter.querySmPayOrderInfo(false);
            }
        });

    }
    private void initCashPayDialog() {
        cashPayDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_cash_pay)
                .setUseRadiusBg(false)
                .setDialogNoConfirm()
                .setDialogTitle("现金支付")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        cashPayDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        etCash = cashPayDialog.getView(R.id.et_cash);
        etCash.setSelectAllOnFocus(true);
        PosKeyBoardView kbCash = cashPayDialog.getView(R.id.kb_cash);
        MoneyFormatUtil.setTextFilter(etCash);
        kbCash.attachTo(etCash, 999999.99, "");
        kbCash.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                mPresenter.settleOrderWithCash(etCash.getText().toString().trim());
            }
        });
    }

    private void initSunMiReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SUNMI_PAY_ACTION);
        registerReceiver(receiver, filter);
    }


    @Override
    protected int getLayout() {
        return R.layout.act_member_detail_new;
    }

    @Override
    public void showToast(String srr) {

    }


    @Override
    public void setMemberDetailData(MemberEntity memberEntity) {
        this.memberEntity = memberEntity;

        tvMemberName.setText(memberEntity.getName());
        if (memberEntity.getGender() == 0) {
            Drawable drawable = getResources().getDrawable(R.drawable.svg_ic_male);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvMemberName.setCompoundDrawables(null, null, drawable, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.svg_ic_female);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvMemberName.setCompoundDrawables(null, null, drawable, null);
        }

        //会员生日
        if (!TextUtils.isEmpty(memberEntity.getBirthday()) && AppDateUtil.isBirthdayDay(new Date(),
                AppDateUtil.timeStamp2Date(memberEntity.getBirthday()))) {
            ivMemberBirthday.setVisibility(View.VISIBLE);
            tvMemberBirthday.setVisibility(View.VISIBLE);
        } else {
            ivMemberBirthday.setVisibility(View.GONE);
            tvMemberBirthday.setVisibility(View.GONE);
        }


        tvMemberPhone.setText(memberEntity.getPhone());
        tvMemberBalance.setText(StringUtils.getFormattedMoneyWithUnit(memberEntity.getCurrentAmount()));
        tvMemberCredit.setText(BigDecimalUtil.getNumber(memberEntity.getMemberPoints()));
        tvLastConsumeContent.setText(!StringUtils.isEmpty(memberEntity.getLastTime()) ?
                AppDateUtil.getDateToString(Long.valueOf(memberEntity.getLastTime()), AppDateUtil.YYYY_MM_DD1) : "-----");
        tvMemberGradeContent.setText(memberEntity.getLevelName());
        tvMemberLevel.setText(memberEntity.getLevelName());

        for (int i = 0; i < (memberEntity.getParamters() == null ? 0 : memberEntity.getParamters().size()); i++) {
            if (memberEntity.getParamters().get(i).getName().equals("年龄")) {
                tvAgeContent.setText(memberEntity.getParamters().get(i).getValue());
            }
            if (memberEntity.getParamters().get(i).getName().equals("与宝宝关系")) {
                tvRelationContent.setText(memberEntity.getParamters().get(i).getValue());
            }
        }

        if (memberEntity.getCurrentState() == 1) {//"怀孕中"
            tvMomStatusContent.setText("怀孕中(预产期：" + AppDateUtil.getDateToString(memberEntity.getConfinementDate(),
                    AppDateUtil.YYYY_MM_DD) + ")");
        } else if (memberEntity.getCurrentState() == 2) {//已有宝宝
            tvMomStatusContent.setText("已有宝宝");
        } else if (memberEntity.getCurrentState() == 3) {//备孕中
            tvMomStatusContent.setText("备孕中");
        }

        tvRegisterTimeContent.setText(AppDateUtil.getTimeStamp(memberEntity.getCreateTime(), AppDateUtil.YYYY_MM_DD2));
        tvIntroduceContent.setText((TextUtils.isEmpty(memberEntity.getExperienceNum()) ? "0" :
                memberEntity.getExperienceNum()) + "人");

        babyAdapter = new ADA_Member_Baby(memberEntity.getId());
        rlvBaby.setAdapter(babyAdapter);
        babyAdapter.setData(memberEntity.getBabys());

        if (memberEntity.getBabys() == null || memberEntity.getBabys().isEmpty()) {
            rlNoBabies.setVisibility(View.VISIBLE);
            rlvBaby.setVisibility(View.GONE);
        } else {
            rlvBaby.setVisibility(View.VISIBLE);
            rlNoBabies.setVisibility(View.GONE);
        }

        final List<String> titles = new ArrayList<>();
        if (!onlySaleGoods) {
            titles.add("次卡(" + (TextUtils.isEmpty(memberEntity.getTimesCardNum()) ? 0 :
                    memberEntity.getTimesCardNum()) + ")");
        }
        titles.add("优惠券(" + (TextUtils.isEmpty(memberEntity.getTicketNum()) ? 0 : memberEntity.getTicketNum()) + ")");
        titles.add("寄存商品(" + (TextUtils.isEmpty(memberEntity.getConsignedNum()) ? 0 : memberEntity.getConsignedNum()) + ")");
        initMagicIndicator(titles, 0);
    }


    @Override
    public void setTimesCardNum(String timesCardNum) {
        mPresenter.getMemberDetail(memberPhone);
//        if (memberEntity == null) {
//            return;
//        }
//        memberEntity.setTimesCardNum(timesCardNum);
//        final List<String> titles = new ArrayList<>();
//        if (!onlySaleGoods) {
//            titles.add("次卡(" + (TextUtils.isEmpty(memberEntity.getTimesCardNum()) ? 0 :
//                    memberEntity.getTimesCardNum()) + ")");
//        }
//        titles.add("优惠券(" + (TextUtils.isEmpty(memberEntity.getTicketNum()) ? 0 : memberEntity.getTicketNum()) + ")");
//        titles.add("寄存商品(" + (TextUtils.isEmpty(memberEntity.getConsignedNum()) ? 0 : memberEntity.getConsignedNum()) + ")");
//        initMagicIndicator(titles, 0);
    }

    @Override
    public void setDepositGoodsNum(String consignedNum) {
        if (memberEntity == null) {
            return;
        }
        memberEntity.setConsignedNum(consignedNum);
        final List<String> titles = new ArrayList<>();
        if (!onlySaleGoods) {
            titles.add("次卡(" + (TextUtils.isEmpty(memberEntity.getTimesCardNum()) ? 0 :
                    memberEntity.getTimesCardNum()) + ")");
        }
        titles.add("优惠券(" + (TextUtils.isEmpty(memberEntity.getTicketNum()) ? 0 : memberEntity.getTicketNum()) + ")");
        titles.add("寄存商品(" + (TextUtils.isEmpty(memberEntity.getConsignedNum()) ? 0 : memberEntity.getConsignedNum()) + ")");
        initMagicIndicator(titles, titles.size() - 1);
    }

    @Override
    public void onSettleRechargeSuccess() {
        PosToast.INSTANCE.makeSuccessToast(mContext, "充值成功");
        closeSettleLoadingButton();
        closeDialog(cashPayDialog, payDialog, bankPosPayDialog, bankDefaultPayDialog, sunMiPayErrorDialog);
        mPresenter.getMemberDetail(memberPhone);
    }

    @Override
    public void resetScanCodeStatus() {
        etScanCode.setText("");
    }

    @Override
    public void showWaitingDialog(boolean isAlipay) {
        showPayDialogByStatus(isAlipay, false, false);
    }

    @Override
    public void showRechargeSettleError(int code, String msg) {
        closeSettleLoadingButton();

        // 根据 code 判断当前是否是超时，超时展示弹窗，否则 toast 提示错误
        switch (code) {
            case SettleAccountPresenter.CODE_BANK_TIME_OUT:
                showBankPayByStatus(true, false);
                break;
            case SettleAccountPresenter.CODE_SUN_MI_TIME_OUT:
            case SettleAccountPresenter.CODE_SUN_MI_NET_ERROR:
                closeDialog(payDialog);
                showDialog(sunMiPayErrorDialog);
                break;
            default:
                // 关闭支付相关的弹窗
                closeDialog(cashPayDialog, payDialog, bankPosPayDialog, bankDefaultPayDialog, sunMiPayErrorDialog);
                showError(msg);
                break;
        }


    }

    @Override
    public void doPrintAfterSettleSuccess(RechargeDetailEntity billDetailEntity) {

        // 发送广播执行打印
        PrinterService.doPrintRechargeTicket(mContext, billDetailEntity, AppConstants.CONFIG_PRINT_COUNT);

    }

    @Override
    public void showTimeChanged(long time) {
        payDialog.setText(R.id.tv_pay_remind_time, String.format("正在等待顾客支付密码 (%sS)", time));
    }

    @Override
    public void openDrawer() {
        PrinterService.openDrawer(mContext);
    }

    @Override
    public void showSunMiPayNetError() {
        if (sunMiPayErrorDialog != null && sunMiPayErrorDialog.isShowing()) {
            LoadingButton lbConfirm = sunMiPayErrorDialog.getView(R.id.lb_refresh);
            lbConfirm.stopLoading("刷新试试");
        }
        showError("网络连接失败");
        closeDialog(payDialog);
        showDialog(sunMiPayErrorDialog);
    }


    private void closeSettleLoadingButton() {

        if (bankDefaultPayDialog != null && bankDefaultPayDialog.isShowing()) {
            LoadingButton loadingButton = bankDefaultPayDialog.getView(R.id.lb_confirm);
            loadingButton.stopLoading("已完成支付");

        }

        if (bankPosPayDialog != null && bankPosPayDialog.isShowing()) {
            lbSendBankPay.stopLoading("立即发送");
            lbSettleDone.stopLoading("已支付成功");
            lbRetryPay.stopLoading("重新发送账单");
        }

        if (sunMiAlertDialog != null && sunMiAlertDialog.isShowing()) {
            sunMiAlertDialog.cancelLoading();
        }

        if (sunMiPayErrorDialog != null && sunMiPayErrorDialog.isShowing()) {
            LoadingButton lbConfirm = sunMiPayErrorDialog.getView(R.id.lb_refresh);
            lbConfirm.stopLoading("刷新试试");
        }

    }

    private void initMagicIndicator(final List<String> titles, int currentIndex) {
        MagicIndicator magicIndicator = findViewById(R.id.indicator_member_detail);
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(Color.parseColor("#FF333333"));
                simplePagerTitleView.setSelectedColor(Color.parseColor("#FF333333"));
                simplePagerTitleView.setText(titles.get(index));
                simplePagerTitleView.setTextSize(18);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mMemberViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_WRAP_CONTENT);
                linePagerIndicator.setColors(Color.parseColor("#FF28282C"));
                return linePagerIndicator;
            }

        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, mMemberViewPager);
        commonNavigator.onPageSelected(currentIndex);
    }

    @OnClick({R.id.iv_back, R.id.iv_more, R.id.tv_add_baby, R.id.ll_member_balance, R.id.ll_member_integral, R.id.btn_recharge
            , R.id.btn_redeem})
    public void toggleEvent(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_more:
                if (memberEntity == null) {
                    ToastUtil.makeText(this, "获取会员信息失败，请退出重试", false);
                    return;
                }
                showPopupWindow();
                break;
            case R.id.tv_add_baby:
                Intent intent = new Intent(ACT_MemberDetail.this, ACT_AddOrModifyBaby.class);
                Bundle bundle = new Bundle();
                bundle.putString("memberId", memberEntity.getId());
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_ADD_BABY);
                break;
            case R.id.ll_member_balance:
                ACT_MemberTransactionRecord.startAc(mContext, memberId);
                break;
            case R.id.ll_member_integral:
                ACT_MemberIntegralRecord.startAc(mContext,memberId);
                break;
            case R.id.btn_recharge:
                showDialog(payTypeSelectDialog);
                break;
            case R.id.btn_redeem:
                if (!StringUtils.isTrue(AppConstants.TEMP_IS_REDEEM_GOODS)) {
                    PosToast.INSTANCE.makeShortToast(mContext, "未设置积分换购功能");
                    return;
                }
                ACT_Redeem.startAc(mContext, memberId, memberPhone, memberEntity.getMemberPoints());
                break;
        }
    }

    private void showPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_member, null);
        TextView tvModifyMember = view.findViewById(R.id.tv_modify_member);
        TextView tvAddBaby = view.findViewById(R.id.tv_add_baby);
        final PopupWindow popupWindow = new PopupWindow(view, DisplayUtil.dip2px(this, 100),
                DisplayUtil.dip2px(this, 100));
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setFocusable(true);//当返回键被按下，这个有焦点先消失。避免直接返回到上个Activity 造成泄漏
        popupWindow.setOutsideTouchable(true);
        int[] location = new int[2];
        ivMore.getLocationOnScreen(location);
        popupWindow.showAtLocation(ivMore, Gravity.NO_GRAVITY, (location[0]) - popupWindow.getWidth() / 2 - 10,
                location[1] + popupWindow.getHeight() / 4);

        //popupWindow在弹窗的时候背景半透明
//        final WindowManager.LayoutParams params = getWindow().getAttributes();
//        params.alpha = 0.5f;
//        getWindow().setAttributes(params);
//        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                params.alpha = 1.0f;
//                getWindow().setAttributes(params);
//            }
//        });

        tvModifyMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ACT_MemberDetail.this, ACT_AddOrModifyMember.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("member", memberEntity);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_MODIFY_MEMBER);
                popupWindow.dismiss();
            }
        });

        tvAddBaby.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ACT_MemberDetail.this, ACT_AddOrModifyBaby.class);
                Bundle bundle = new Bundle();
                bundle.putString("memberId", memberEntity.getId());
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_ADD_BABY);
                popupWindow.dismiss();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {

            switch (requestCode) {
                case REQUEST_CODE_MODIFY_MEMBER:
                    MemberEntity memberEntity = (MemberEntity) data.getSerializableExtra("memberEntity");
                    setMemberDetailData(memberEntity);
                    RxBus.getDefault().post(new MemberBindEvent(memberEntity));
                    break;
                case REQUEST_CODE_ADD_BABY: {
                    MemberEntity.BabysBean baby = (MemberEntity.BabysBean) data.getSerializableExtra("baby");
                    babyAdapter.appendData(baby);
                    if (rlNoBabies.getVisibility() == View.VISIBLE) {
                        rlNoBabies.setVisibility(View.GONE);
                        rlvBaby.setVisibility(View.VISIBLE);
                    }
                    break;
                }
                case REQUEST_CODE_MODIFY_BABY:
                    MemberEntity.BabysBean baby = (MemberEntity.BabysBean) data.getSerializableExtra("baby");
                    int index = babyAdapter.getData().indexOf(baby);
                    babyAdapter.getData().set(index, baby);
                    babyAdapter.notifyItemChanged(index);
                    break;
            }
        }
    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (SUNMI_PAY_ACTION.equals(action) && mPresenter.isRecharge()) {
                mPresenter.setRecharge(false);
                String jsonStr = intent.getStringExtra("response");
                Elog.e("SUNMI_PAY", "返回参数：" + jsonStr);
                mPresenter.querySmPayOrderInfo(true);
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog(cashPayDialog, payDialog, bankPosPayDialog, bankDefaultPayDialog);
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    public static void startAc(Context context, String memberId, String memberPhone) {
        Intent intent = new Intent(context, ACT_MemberDetail.class);
        intent.putExtra("memberId", memberId);
        intent.putExtra("memberPhone", memberPhone);
        context.startActivity(intent);
    }

    @Override
    protected View getTargetView() {
        return clRootView;
    }


}
